import datetime

from src.service import RoleManageService
from src.util.Service import *
from src.util.PwdUtil import createHashPwd


# 查询所有用户信息（分页）
def getUserAll(page: Page = Page(), cdn=None):
    if cdn is None:
        cdn = {}
    users = User.getAllUser(page, cdn)
    return users


# 根据用户id查询用户信息
def getUserInfo(user_id):
    user = User.getUserById(user_id)
    rids = UserRole.getUserRoles(user_id)
    roles = Role.getRolesInId(rids)
    return {
        'user': user,
        'roles': roles
    }


# 获取用户基本信息
def getUserBaseInfo(user_id):
    return User.getUserById(user_id)


# 根据用户的uid 和 rid 查询用户拥有的菜单
def getUserMenusByUidAndRid(uid: int, rid: int):
    if UserRole.hasUserRole(uid, rid):
        menus = RoleManageService.getMenusByRId(rid)
        g_ids = GroupUser.getUserGroupByUid(uid)
        m_ids = GroupAuth.getAuth(g_ids, 'menu')
        menus.extend(Menu.getMenusInMIds(m_ids))
        return menus
    return []


# 根据用户的uid 和 rid 查询用户的所有菜单按钮
def getUserMenuHandle(uid: int, rid: int):
    if UserRole.hasUserRole(uid, rid):
        gids = GroupUser.getUserGroupByUid(uid)
        tags = GroupAuth.getAuth(gids, 'button')
        mids = GroupAuth.getAuth(gids, 'menu')
        mids = [int(item) for item in mids]
        smh = MenuButton.getAllMenuHandleInMids(mids)
        data: dict = RoleManageService.getMenuHandles(rid)
        dt: list[str] = data.get('tags')
        dt.extend(tags)
        dmh: list = data.get('smh')
        dmh.extend(smh)
        return data
    return {'smh': [], 'tags': []}


# 根据用户id查询用户状态
def getUserStatus(uid):
    r = User.getUserById(uid)
    if r is not None:
        return r['status']


# 添加用户
def addUser(data: dict):
    username = data['username']
    if User.hasUserByUsername(username):
        return 2
    if len(username) < 8:
        return 3
    pwd = createHashPwd(username, data['password'])
    data['password'] = pwd
    data: dict = formatParam(data, ['uId'])
    data['initTime'] = datetime.utcnow()
    data['status'] = '1'
    data['sex'] = '0'
    data['head'] = 'User'
    User.addUser(data)
    return True


# 修改用户信息(nickname,sex,head...)
def updateUser(data: dict):
    uid = data['uId']
    data = formatParam(data, ['uId', 'username', 'password', 'initTime'])
    User.updateById(uid, data)
    return True


# 修改用户密码
def resetPwd(u_id: int, pwd: str):
    if u_id == 1:
        return False
    user = User.getUserById(u_id)
    if user is None:
        return False
    User.updateById(u_id, {'password': createHashPwd(user['username'], pwd)})
    return True


# 用户修改密码
def updatePwd(user_id: int, d: dict):
    user = User.getUserById(user_id, True)
    if user is None:
        return False
    username = user['username']
    old = d['oPwd']
    nPwd = d['pwd']
    # 判断是否与原密码相等
    oldPwdHash = createHashPwd(username, old)
    if oldPwdHash != user['password']:
        return 2
    if len(nPwd) < 8:
        return 3
    User.updateById(user_id, {'password': createHashPwd(username, nPwd)})
    return True


# 删除用户
def delUser(u_ids: list[int]):
    # 在用户角色映射表中删除 mid 的映射关系
    database.transaction()
    try:
        with database.atomic():
            if 1 in u_ids:
                return False
            UserRole.delUserRoleInUid(u_ids)
            UserStatus.delUserStatusInUid(u_ids)
            User.delUserById(u_ids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 查看用户拥有的角色
def getUserRoles(uid):
    rids = UserRole.getUserRoles(uid)
    roles = Role.getRolesInId(rids)
    return {'roles': roles}


# 查看用户拥有的角色的名字
def getUserRolesName(uid):
    rids = UserRole.getUserRoles(uid)
    roles = Role.getRoleNameInIsd(rids)
    return roles


# 添加用户的角色
def uploadUserRoles(uid, rids):
    if uid == 1:
        return False
    can_add_rids = list()
    not_add_rids = list()
    try:
        database.begin()
        UserRole.delUserRoleInUid([uid])
        for rid in rids:
            if Role.hasRole(rid) and not UserRole.hasUserRole(uid, rid):
                can_add_rids.append(rid)
            else:
                not_add_rids.append(rid)
        UserRole.addUserRole(uid, can_add_rids)
        database.commit()
        return True
    except:
        database.rollback()
        return False


# 启用和禁用某用户

def userUpdateStatus(id, k):
    return False


# 上传用户头像
def userUpdateHead(uid, filepath):
    return False
